<template>
  <div class="fit row no-wrap justify-between items-start">
    <qx-tree v-model="selected" :filter-method="filterMethod" :loading="loading" :options="OrgTrees" :props="props"
             classes="full-height col bg-white" defaultExpandAll multiple strategy="strict" @change="treeChange">
      <template v-slot:tree-top>
        <div class="org-cfg-btn q-gutter-sm q-mb-sm row items-center">
          <q-btn v-auth="['memberOrg:save']" color="primary" icon="add" unelevated @click="handleCreate">
            {{ $t('Add') }}
          </q-btn>
          <q-btn v-auth="['memberOrg:delete']" :disable="isDisable" icon="delete" outline text-color="primary"
                 @click="handleDelete">
            {{ $t('Del') }}
          </q-btn>
        </div>
      </template>
      <template v-slot:header="{ prop }">
        <div class="row items-center">
          <div class="text-weight-bold">{{ prop.node.code }} -- {{ prop.node[toI18nName('orgNameZhCn')] }}</div>
        </div>
      </template>
      <template v-slot:body="{ prop }">
        <span>{{ prop.node.remark }}</span>
      </template>
    </qx-tree>
    <q-card class="col q-pa-md q-ml-md">
      <span class="text-h5">{{ $t('SystemCore.OrgBasicInfo') }}</span>
      <q-separator class="q-mt-sm q-mb-md"></q-separator>
      <qx-form ref="OrgForm" v-model="formInfo" :option="formOption" @submit="submitHandle"></qx-form>
    </q-card>
  </div>
</template>

<script setup>
import { i18n, toI18nName } from 'boot/i18n'
import { deleteAPI, postAPI, putAPI } from 'src/api'
import { isAuth } from 'src/directives/v-auth'
import { createDialog, deepClone } from 'src/utils/utils'
import { computed, ref } from 'vue'

const OrgTrees = ref([])
const formInfo = ref({})
const selected = ref([])
const OrgForm = ref(null)
const orgTypeList = ref([])
const parentOrges = ref([])
const props = { label: toI18nName('orgNameZhCn'), children: 'childs' }

const readonly = computed(() => {
  return formInfo.value.sysInner === '1' || !isAuth(['memberOrg:save', 'memberOrg:update'])
})
const isDisable = computed(() => formInfo.value.sysInner === '1' || !(formInfo.value && formInfo.value.id))
const formOption = computed(() => {
  return {
    labelWidth: 100, searchLabelWidth: 70, readonly: readonly.value, menuBtn: !readonly.value, span: 22,
    column: [{
      label: `${i18n.t('SystemCore.SuperiorOrg')}`, field: 'parentId', type: 'tree', options: parentOrges.value,
      props, value: OrgTrees.value[0]?.id, required: true
    }, {
      label: `${i18n.t('SystemCore.OrgType')}`,
      field: 'orgType',
      type: 'select',
      options: orgTypeList.value,
      props: {
        label: toI18nName('dictNameZhCn'), value: 'dictKey'
      },
      required: true
    }, {
      label: `${i18n.t('SystemCore.OrgCode')}`,
      field: 'code',
      required: true
    }, {
      label: `${i18n.t('SystemCore.OrgNameENUS')}`,
      field: 'orgNameEnUs'
    }, {
      label: `${i18n.t('SystemCore.OrgName')}`,
      field: 'orgNameZhCn',
      required: true
    }, {
      label: `${i18n.t('Sorting')}`,
      field: 'sortId',
      type: 'number',
      min: 0,
      decimals: 0,
      display: false,
      required: true
    }, {
      label: `${i18n.t('Remarks')}`,
      field: 'remark',
      type: 'textarea',
      maxlength: 200
    }]
  }
})

const loading = ref(false)

const initOrgType = () => {
  const params = {
    pageSize: '-1',
    andDynamicQueryItems: [{ property: 'dictTypeCode', value: 'SYS_ORG_TYPE', criterion: 'andEqualTo' }],
    orderByItems: [{ property: 'sortId', orderType: 'ASC' }]
  }
  postAPI('/config/api/cfgDictData/list', params, data => {
    orgTypeList.value = data.rows
  })
}
initOrgType()

const initOrgTrees = () => {
  if (!loading.value) loading.value = true
  const params = {}
  OrgTrees.value = []
  postAPI('/member/api/memberOrg/listTree', params, data => {
    OrgTrees.value = data
    parentOrges.value = [{ orgNameZhCn: '无', orgNameEnUs: 'Nothing', id: '-1' }, ...data]
    loading.value = false
  }, () => {
    loading.value = false
  })
}
initOrgTrees()

const treeChange = (target, node) => {
  if (target && target.length > 1) {
    selected.value = [target[1]]
    formInfo.value = deepClone(node[1] || {})
    return
  }
  formInfo.value = deepClone(node[0] || {})
}

const handleCreate = () => {
  selected.value = []
  const { children = [], id: parentId } = formInfo.value
  formInfo.value = { parentId, sortId: children.length + 1 }
}
const handleReset = () => {
  selected.value = []
  formInfo.value = {}
}
const handleDelete = () => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/member/api/memberOrg/${formInfo.value.id}`, {}, () => {
      handleReset()
      initOrgTrees()
    })
  }, () => {})
}

const submitHandle = (form, done) => {
  const API = form.id ? putAPI : postAPI
  API('/member/api/memberOrg', form, () => {
    initOrgTrees()
    done()
    handleReset()
  }, () => done())
}

const filterMethod = (node, filter) => {
  const query = (filter || '').toUpperCase()
  if ((node.code || '').toUpperCase().includes(query)) return true
  return (node[toI18nName('orgNameZhCn')] || '').toUpperCase().includes(query)
}
</script>